import base64
import pickle

from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, response, user):
    # 合并操作
    # 获取cookie
    cart_cookie = request.COOKIES.get('cart_cookie')
    # cookie数据判断、
    if not cart_cookie:
        return response
    # 数据解密
    cart = pickle.loads(base64.b64decode(cart_cookie.encode()))

    # 拆分数据
    data_dict = {}  # 保存hash数据 {10:2, 11:3}
    # 用列表保存选中状态
    cart_selected = []  # 保存选中状态的sku——id
    cart_selected_no = []  # 保存未选中状态的sku——id

    if cart:
        for sku_id, count_dict in cart.items():
            # hash保存
            data_dict[int(sku_id)] = int(count_dict['count'])
            # 选中状态保存
            if count_dict['selected']:
                cart_selected.append(sku_id)
            else:
                cart_selected_no.append(sku_id)

        # 保存数据
        conn = get_redis_connection('cart')
        # 保存hash
        conn.hmset('cart_%s' % user.id, data_dict)
        # 更新选中状态
        if cart_selected:
            conn.sadd('cart_selected_%s' % user.id, *cart_selected)
        if cart_selected_no:
            conn.srem('cart_selected_%s' % user.id, *cart_selected_no)

    # 删除cookie
    response.delete_cookie('cart_cookie')
    # 返回数据
    return response
